package de.upb.messerschmidt.set;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.gson.Gson;

import de.upb.messerschmidt.set.entity.Contact;
import de.upb.messerschmidt.set.entity.Person;
import de.upb.messerschmidt.set.jdo.PMF;

/**
 * This Servlet returns the names of all {@link Contact}s for a specific user.
 * 
 * @author Tim Messerschmidt
 * 
 */
public class GetContactServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String prename = req.getParameter("prename");
		String name = req.getParameter("name");

		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query query = pm.newQuery(Person.class);
		query.setFilter("prename == prenameString && name == nameString");
		query.declareParameters("String prenameString, String nameString");

		try {
			List<Person> results = (List<Person>) query.execute(prename, name);

			if (!results.isEmpty()) {
				Person result = results.get(0);

				List<Key> contactKeys = result.getContacts();
				List<Person> toJson = new ArrayList<Person>();
				for (Key key : contactKeys) {
					Query contactQuery = pm.newQuery(Contact.class);
					contactQuery.setFilter("key == keyParam");
					contactQuery.declareParameters("Key keyParam");
					contactQuery
							.declareImports("import com.google.appengine.api.datastore.Key");

					List<Contact> contacts = (List<Contact>) contactQuery
							.execute(key);

					if (!contacts.isEmpty()) {
						for (Contact c : contacts) {
							Query personQuery = pm.newQuery(Person.class);
							personQuery.setFilter("key == keyParam");
							personQuery.declareParameters("Key keyParam");
							personQuery
									.declareImports("import com.google.appengine.api.datastore.Key");

							List<Person> persons = (List<Person>) personQuery
									.execute(c.getContact());

							if (!persons.isEmpty()) {
								for (Person p : persons) {
									toJson.add(p);
								}
							}
						}
					}
				}
				if (toJson.isEmpty()) {
					resp.setStatus(200);
					resp.getWriter().println("no contacts yet");
				} else {
					Gson gson = new Gson();
					String json = gson.toJson(toJson);
					resp.setStatus(200);
					resp.getWriter().println(URLEncoder.encode(json, "UTF-8"));
				}
			} else {
				resp.setStatus(200);
				resp.getWriter().println("no contacts yet");
			}
		} finally {
			query.closeAll();
			pm.close();
		}
	}
}
